import { ArticleComment } from "./entities/comment.entity";


export function buildCommentTree(comments: ArticleComment[]): ArticleComment[] {
    const commentMap = new Map<any, ArticleComment>();
    const roots: ArticleComment[] = [];

    // 先将所有评论保存到 Map 中
    for (const comment of comments) {
        comment.replies = [];
        commentMap.set(comment.id, comment);
    }

    // 遍历所有评论，将每个评论添加到其父评论的子评论列表中
    for (const comment of comments) {
        if (comment.parent) {
            const parent = commentMap.get(comment.parent.id);
            if (parent) {
                parent.replies.push(comment);
            }
        } else {
            roots.push(comment);
        }
    }
    // roots.reverse()
    return roots;
}